package com.gexiaobao.pigeon.app.util

import android.app.Activity
import android.content.Intent
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Build
import android.util.DisplayMetrics
import java.util.Locale

/**
 * @Author      : hxw
 * @Date        : 2024/10/31 16:02
 * @Describe    :
 */
object LanguageUtil {

    /*语言类型：
    * 此处支持3种语言类型，更多可以自行添加。
    * */
    private const val ENGLISH = "en"
    private const val CHINESE = "ch"
    private const val PORTUGUES = "pt"
    private const val TRADITIONAL_CHINESE = "zh_rTW"

    private val languagesList = hashMapOf<String, Locale>(
        ENGLISH to Locale.ENGLISH,
        CHINESE to Locale.CHINESE,
        PORTUGUES to Locale("pt", "BR"), // 葡萄牙语（巴西）
        TRADITIONAL_CHINESE to Locale("zh", "TW")
    )

    /**
     * 修改语言
     *
     * @param activity 上下文
     * @param language 例如修改为 英文传“en”，参考上文字符串常量
     * @param cls      要跳转的类（一般为入口类）
     */
    fun changeAppLanguage(activity: Activity, language: String, cls: Class<*>) {
        val resources: Resources = activity.resources
        val configuration: Configuration = resources.configuration

        // app locale 默认简体中文
        val locale = getLocaleByLanguage(language.ifEmpty { "zh" })
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(locale)
        } else {
            configuration.locale = locale
        }

        val dm: DisplayMetrics = resources.displayMetrics
        resources.updateConfiguration(configuration, dm)

        // 重启app
        val intent = Intent(activity, cls)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        activity.startActivity(intent)
        //加载动画
        // activity.overridePendingTransition(R.anim.anim_right_in, R.anim.anim_left_out)
        // activity.overridePendingTransition(0, 0)
    }

    /**
     * 获取指定语言的locale信息，如果指定语言不存在
     * 返回本机语言，如果本机语言不是语言集合中的一种，返回英语
     */
    private fun getLocaleByLanguage(language: String): Locale {
        return if (isContainsKeyLanguage(language)) {
            languagesList[language] ?: Locale.ENGLISH
        } else {
            val locale = Locale.getDefault()
            for (key in languagesList.keys) {
                if (languagesList[key]?.language == locale.language) {
                    return locale
                }
            }
            Locale.ENGLISH
        }
    }

    /**
     * 如果此映射包含指定键的映射关系，则返回 true
     */
    private fun isContainsKeyLanguage(language: String): Boolean {
        return languagesList.containsKey(language)
    }

}